<?php
/**
 * Function:
 * Description:
 * Abo 2019/3/20 00:15
 * Email: abo2013@foxmail.com
 */
namespace Abo\Smartsync\Traits;

use Abo\Smartsync\Logic\CreateDBTableLogic;
use Abo\Smartsync\Logic\SyncDataIntoTableLogic;
use Illuminate\Support\Facades\DB;

trait SmartSyncTrait
{
    protected $tableName, $tablePrimaryId, $updateBatch;

    /** 同步数据 */
    public function smartSyncData( array $data = [], $BusinessClient )
    {
        $DBTableCreateLogic = new CreateDBTableLogic( $this->tableName, $this->tablePrimaryId );
        $SyncDataIntoTableLogic = new SyncDataIntoTableLogic( $this->tableName, $BusinessClient );

        $this->updateBatch = $SyncDataIntoTableLogic->updateBatch;

        //TODO 提取特征
        $ret2CreateTable = $DBTableCreateLogic->createSyncTableByData( current( $data ) ); // 生成表结构
        return $ret2SyncData = $SyncDataIntoTableLogic->syncDataIntoTable( $data );
    }

    /** 获取 新增同步数据 */
    protected function getNewSyncList()
    {
        if ( !$this->updateBatch ) {
            return [];
        }

        $newSyncList = \DB::table( $this->tableName )
            ->where( 'remove_time', '=', 0 )
            ->where( 'update_batch', '=', $this->updateBatch )
            ->where( 'md5_origin', '=', '' )
            ->where( 'md5_new', '!=', '' )
            ->get();

        //$sql2Str = "SELECT * FROM sync_game_index WHERE update_batch = '{$this->updateBatch}' AND md5_origin = '' AND md5_new <> ''";
        //$newSyncList = \DB::table()->groupBy();

        if ( !$newSyncList ) {
            return [];
        }

        return $newSyncList->toArray();
    }

    /** 获取 变更同步数据 */
    protected function getChangeSyncList()
    {
        if ( !$this->updateBatch ) {
            return [];
        }

        $changeSyncList = \DB::table( $this->tableName )
            ->where( 'remove_time', '=', 0 )
            ->where( 'update_batch', '=', $this->updateBatch )
            ->where( 'md5_origin', '!=', '' )
            ->where( 'md5_new', '!=', DB::raw( 'md5_origin' ) ) // 还可以补充其他 业务逻辑条件,搜索出特定逻辑数据
            ->get();

        if ( !$changeSyncList ) { return []; }

        return $changeSyncList->toArray();
    }

    /** 获取 失联同步数据 */
    protected function getUnsetSyncList()
    {
        if ( !$this->updateBatch ) {
            return [];
        }

        $unsetSyncList = \DB::table( $this->tableName )
            ->where( 'update_batch', '!=', $this->updateBatch )
            ->where( 'md5_origin', '!=', '' )
            ->where( 'md5_new', '=', '' )
            ->get();

        if ( !$unsetSyncList ) { return []; }

        return $unsetSyncList->toArray();
    }

    /** 设置表名 */
    public function setTableName($tableName): void
    {
        $this->tableName = $tableName;
    }

    /** 设置表主键ID */
    public function setTablePrimaryId($tablePrimaryId): void
    {
        $this->tablePrimaryId = $tablePrimaryId;
    }
}